import {createRouter, createWebHistory} from "vue-router";

const Layout = () => import('@/layout/index.vue')
const CLayout = () => import('@/layout/CLayout.vue')
const modules = import.meta.glob("../views/**/**.vue");

export function transformRoutes(menus) {
    const asyncRoutes = []
    menus.forEach(menu => {
        let tmp = {
            path: menu.path,
            name: menu.code,
            component: '',
            children: [],
            redirect: menu.redirect_path,
            props: {},
            meta: {
                title: menu?.title || '',
                icon: menu?.icon || '',
                keepAlive: menu?.keep_alive || false,
                hidden: menu?.hidden || false,
                type: menu?.type || 0,
                btns: menu?.btns || [],
            },
        }
        if (menu.component.toString() === 'Layout') {
            tmp.component = Layout
        } else if (menu.component.toString() === 'CLayout') {
            tmp.component = CLayout()
        } else {
            const component = modules[`../views/${menu.component}`];
            if (component) {
                tmp.component = component
            } else {
                tmp.component = modules["../views/error/404.vue"]
            }
        }
        tmp.children = transformRoutes(menu?.children || [])
        asyncRoutes.push(tmp)
    })
    return asyncRoutes
}

export const devRoutes = [
    {
        path: "/dev",
        name: "Developer",
        component: Layout,
        meta: {title: "开发工具", icon: 'Monitor'},
        children: [
            {
                path: "component",
                name: "DevComponent",
                component: () => import('@/views/dev/component.vue'),
                meta: {title: "Vue页面", icon: 'Document'},
            },
            {
                path: "permission",
                name: "DevPermission",
                component: () => import('@/views/dev/permission.vue'),
                meta: {title: "接口权限", icon: 'Operation'},
            }
        ]
    }
];

const constantRoutes = [
    {
        path: "/login",
        name: "Login",
        component: () => import("@/views/login/index.vue"),
        meta: {hidden: true, title: "登录"},
    },
    {
        path: '/404',
        component: () => import('@/views/error/404.vue'),
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    scrollBehavior: () => ({left: 0, top: 0}),
})

export default router;